package com.ms.p2p.controller;

import com.ms.common.bean.Message;
import com.ms.p2p.Constants;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.ms.common.utils.ResponseUtils.*;
@Controller
@RequestMapping(value = "/system/upload", method = RequestMethod.POST)
public class UploadController {

    @RequestMapping(value="/test", method=RequestMethod.POST)
    public String submit(@RequestParam(value = "file", required = false) MultipartFile multipartFile,
                         String componentId, HttpServletResponse response){

        String path = null;
        if (path == null){
            return ajaxJson(Message.error("上传地址错误", null), response);
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("url", path);
        return ajaxJson(map, response);

    }
    @RequestMapping(value = "/editor", method = RequestMethod.POST)
    @ResponseBody
    public String editor(HttpServletRequest request, HttpServletResponse response) throws FileUploadException {

        String savePath = Constants.UPLOAD_LOCAL_PATH + "/resources/file/";
        String saveUrl  = "/resources/file/";
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        long maxSize = 1024 * 1024;
        if(!ServletFileUpload.isMultipartContent(request)){
            return getCoder("请选择文件。");
        }
        File uploadDir = new File(savePath);
        if(!uploadDir.isDirectory()){
            return getCoder("上传目录不存在。"+uploadDir);
        }
        if(!uploadDir.canWrite()){
            return getCoder("上传目录没有写权限。");

        }
        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if(!extMap.containsKey(dirName.split("/")[0])){
            return getCoder("目录名不正确。");
        }
//创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //检查文件大小
                if(item.getSize() > maxSize){
                    return getCoder("上传文件大小超过限制,最大为1MB");

                }
                //检查扩展名
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if(!Arrays.<String>asList(extMap.get(dirName.split("/")[0]).split(",")).contains(fileExt)){
                    return getCoder("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");

                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try{
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                }catch(Exception e){
                    return getCoder("上传文件失败。");

                }

                JSONObject obj = new JSONObject();
                obj.put("code", 0);
                obj.put("msg", "成功");
                JSONObject data = new JSONObject();
                data.put("src",saveUrl + newFileName);
                data.put("title","图片");
                obj.put("data",data);
                return obj.toString();
                //	out.println(saveUrl + newFileName);
            }
        }
        return null;
    }
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public String upload(HttpServletRequest request, HttpServletResponse response) throws FileUploadException {


        String savePath = Constants.UPLOAD_LOCAL_PATH + "/resources/file/";

        String saveUrl  = "/resources/file/";
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        long maxSize = 1024 * 1024;
        if(!ServletFileUpload.isMultipartContent(request)){
            return getError("请选择文件。");
        }
        File uploadDir = new File(savePath);
        if(!uploadDir.isDirectory()){
            return getError("上传目录不存在。"+uploadDir);
        }
        if(!uploadDir.canWrite()){
            return getError("上传目录没有写权限。");

        }
        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if(!extMap.containsKey(dirName.split("/")[0])){
            return getError("目录名不正确。");
        }
//创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //检查文件大小
                if(item.getSize() > maxSize){
                    return getError("上传文件大小超过限制,最大为1MB");

                }
                //检查扩展名
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if(!Arrays.<String>asList(extMap.get(dirName.split("/")[0]).split(",")).contains(fileExt)){
                    return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");

                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try{
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                }catch(Exception e){
                    return getError("上传文件失败。");

                }

                JSONObject obj = new JSONObject();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);
                return obj.toString();
                //	out.println(saveUrl + newFileName);
            }
        }
        return null;
    }
    public String getError(String message){
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toString();
    }
    public String getCoder(String message){
        JSONObject obj = new JSONObject();
        obj.put("code", 1);
        obj.put("msg", message);
        return obj.toString();
    }
}
